﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace BlinkyDevice
{
    public partial class UsbSearchForm : Form
    {
        /// <summary>HID Guid</summary>
        Guid deviceGuid;
        /// <summary>Handle returned by RegisterForUsbEvents - used for unregistering</summary>
        IntPtr UsbEventHandle;

        /// <summary>
        /// Constructor
        /// </summary>
        public UsbSearchForm()
        {
            InitializeComponent();
            deviceGuid = UsbImports.HIDGuid;
        }

        /// <summary>
        /// Accessor for device GUID
        /// </summary>
        public Guid getGuid
        {
            get
            {
                return deviceGuid;
            }
        }

        public event EventHandler DeviceArrived;

        public event EventHandler DeviceRemoved;

        protected virtual void OnDeviceArrived(EventArgs args)
        {
            if (DeviceArrived != null)
            {
                DeviceArrived(this, args);
            }
        }

        protected virtual void OnDeviceRemoved(EventArgs args)
        {
            if (DeviceRemoved != null)
            {
                DeviceRemoved(this, args);
            }
        }

        protected override void OnHandleCreated(EventArgs e)
        {
            base.OnHandleCreated(e);
            UsbEventHandle = UsbImports.RegisterForUsbEvents(Handle, deviceGuid);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == UsbImports.WM_DEVICECHANGE)	// we got a device change message! A USB device was inserted or removed
            {
                switch (m.WParam.ToInt32())	// Check the W parameter to see if a device was inserted or removed
                {
                    case UsbImports.DEVICE_ARRIVAL:	// inserted
                        OnDeviceArrived(new EventArgs());
                        break;
                    case UsbImports.DEVICE_REMOVECOMPLETE:	// removed
                        OnDeviceRemoved(new EventArgs());
                        break;
                }
            }
            base.WndProc(ref m);	// pass message on to base form
        }
    }
}
